package view;

import entity.*;
import service.*;
import util.DateUtil;
import util.IDGenerator;
import util.LogUtil;

import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class ManagerView {
    private Scanner scanner = new Scanner(System.in);
    private IUserService userService = new UserServiceImpl();
    private IMovieService movieService = new MovieServiceImpl();
    private IScheduleService scheduleService = new ScheduleServiceImpl();
    private ITicketService ticketService = new TicketServiceImpl();
    private User currentUser;

    public void showManagerView(User user) {
        currentUser = user;
        while (true) {
            System.out.println("===== 经理界面 =====");
            System.out.println("1. 影片管理");
            System.out.println("2. 排片管理");
            System.out.println("3. 销售数据查看");
            System.out.println("4. 修改密码");
            System.out.println("5. 退出登录");
            System.out.print("请选择操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    showMovieManagementMenu();
                    break;
                case "2":
                    showScheduleManagementMenu();
                    break;
                case "3":
                    showSalesDataMenu();
                    break;
                case "4":
                    modifyPassword();
                    break;
                case "5":
                    System.out.println("退出登录！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    private void showMovieManagementMenu() {
        while (true) {
            System.out.println("===== 影片管理 =====");
            System.out.println("1. 添加影片");
            System.out.println("2. 删除影片");
            System.out.println("3. 修改影片");
            System.out.println("4. 查询影片");
            System.out.println("5. 列出所有影片");
            System.out.println("6. 返回上一级");
            System.out.print("请选择操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addMovie();
                    break;
                case "2":
                    deleteMovie();
                    break;
                case "3":
                    modifyMovie();
                    break;
                case "4":
                    searchMovie();
                    break;
                case "5":
                    listAllMovies();
                    break;
                case "6":
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    private void addMovie() {
        System.out.print("请输入影片 ID：");
        String movieId = scanner.nextLine();
        System.out.print("请输入影片名称：");
        String name = scanner.nextLine();
        System.out.print("请输入导演：");
        String director = scanner.nextLine();
        System.out.print("请输入主演：");
        String stars = scanner.nextLine();
        System.out.print("请输入剧情简介：");
        String description = scanner.nextLine();
        System.out.print("请输入时长（分钟）：");
        int duration = Integer.parseInt(scanner.nextLine());
        System.out.print("请输入评分（0-10）：");
        double rating = Double.parseDouble(scanner.nextLine());

        Movie movie = new Movie(movieId, name, director, stars, description, duration, rating);
        boolean result = movieService.addMovie(movie);
        if (result) {
            LogUtil.log("INFO", "添加影片成功，影片 ID：" + movieId, currentUser.getUsername());
            System.out.println("添加影片成功！");
        } else {
            System.out.println("添加影片失败！");
        }
    }

    private void deleteMovie() {
        System.out.print("请输入要删除的影片 ID：");
        String movieId = scanner.nextLine();

        boolean result = movieService.deleteMovie(movieId);
        if (result) {
            LogUtil.log("INFO", "删除影片成功，影片 ID：" + movieId, currentUser.getUsername());
            System.out.println("删除影片成功！");
        } else {
            System.out.println("删除影片失败！");
        }
    }

    private void modifyMovie() {
        System.out.print("请输入要修改的影片 ID：");
        String movieId = scanner.nextLine();

        Movie movie = movieService.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("请输入新的影片名称（留空则不修改）：");
        String name = scanner.nextLine();
        if (!name.isEmpty()) {
            movie.setName(name);
        }

        System.out.print("请输入新的导演（留空则不修改）：");
        String director = scanner.nextLine();
        if (!director.isEmpty()) {
            movie.setDirector(director);
        }

        System.out.print("请输入新的主演（留空则不修改）：");
        String stars = scanner.nextLine();
        if (!stars.isEmpty()) {
            movie.setStars(stars);
        }

        System.out.print("请输入新的剧情简介（留空则不修改）：");
        String description = scanner.nextLine();
        if (!description.isEmpty()) {
            movie.setDescription(description);
        }

        System.out.print("请输入新的时长（留空则不修改）：");
        String durationStr = scanner.nextLine();
        if (!durationStr.isEmpty()) {
            int duration = Integer.parseInt(durationStr);
            movie.setDuration(duration);
        }

        System.out.print("请输入新的评分（留空则不修改）：");
        String ratingStr = scanner.nextLine();
        if (!ratingStr.isEmpty()) {
            double rating = Double.parseDouble(ratingStr);
            movie.setRating(rating);
        }

        boolean result = movieService.updateMovie(movie);
        if (result) {
            LogUtil.log("INFO", "修改影片成功，影片 ID：" + movieId, currentUser.getUsername());
            System.out.println("修改影片成功！");
        } else {
            System.out.println("修改影片失败！");
        }
    }

    private void searchMovie() {
        System.out.print("请输入影片名称（留空则不限制）：");
        String name = scanner.nextLine();
        System.out.print("请输入导演（留空则不限制）：");
        String director = scanner.nextLine();
        System.out.print("请输入主演（留空则不限制）：");
        String stars = scanner.nextLine();

        List<Movie> movies = movieService.searchMovies(name, director, stars);
        System.out.println("===== 影片列表 =====");
        System.out.println("影片 ID\t影片名称\t导演\t主演\t评分");
        for (Movie movie : movies) {
            System.out.println(movie.getMovieId() + "\t" + movie.getName() + "\t" +
                    movie.getDirector() + "\t" + movie.getStars() + "\t" + movie.getRating());
        }
    }

    private void listAllMovies() {
        List<Movie> movies = movieService.getAllMovies();
        System.out.println("===== 影片列表 =====");
        System.out.println("影片 ID\t影片名称\t导演\t主演\t评分");
        for (Movie movie : movies) {
            System.out.println(movie.getMovieId() + "\t" + movie.getName() + "\t" +
                    movie.getDirector() + "\t" + movie.getStars() + "\t" + movie.getRating());
        }
    }

    private void showScheduleManagementMenu() {
        while (true) {
            System.out.println("===== 排片管理 =====");
            System.out.println("1. 增加场次");
            System.out.println("2. 修改场次");
            System.out.println("3. 删除场次");
            System.out.println("4. 列出场次");
            System.out.println("5. 自动排片");
            System.out.println("6. 返回上一级");
            System.out.print("请选择操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    addSchedule();
                    break;
                case "2":
                    modifySchedule();
                    break;
                case "3":
                    deleteSchedule();
                    break;
                case "4":
                    listSchedules();
                    break;
                case "5":
                    autoGenerateSchedule();
                    break;
                case "6":
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    private void addSchedule() {
        System.out.print("请输入影片 ID：");
        String movieId = scanner.nextLine();
        Movie movie = movieService.getMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("请输入放映厅 ID（H000001-黄金厅，H000002-白银厅，H000003-翡翠厅，H000004-钻石厅，H000005-宝石厅）：");
        String hallId = scanner.nextLine();
        CinemaHall hall = null;
        for (CinemaHall h : ((ScheduleServiceImpl) scheduleService).cinemaHalls) {
            if (h.getHallId().equals(hallId)) {
                hall = h;
                break;
            }
        }
        if (hall == null) {
            System.out.println("放映厅不存在！");
            return;
        }

        System.out.print("请输入开始时间（格式：yyyy-MM-dd HH:mm:ss）：");
        String startTimeStr = scanner.nextLine();
        Date startTime = DateUtil.parseDate(startTimeStr);

        System.out.print("请输入票价：");
        double price = Double.parseDouble(scanner.nextLine());

        Schedule schedule = new Schedule();
        schedule.setScheduleId(IDGenerator.generateScheduleId());
        schedule.setMovie(movie);
        schedule.setCinemaHall(hall);
        schedule.setStartTime(startTime);
        schedule.setPrice(price);

        boolean result = scheduleService.addSchedule(schedule);
        if (result) {
            LogUtil.log("INFO", "增加场次成功，场次 ID：" + schedule.getScheduleId(), currentUser.getUsername());
            System.out.println("增加场次成功！");
        } else {
            System.out.println("增加场次失败！");
        }
    }

    private void modifySchedule() {
        System.out.print("请输入要修改的场次 ID：");
        String scheduleId = scanner.nextLine();

        Schedule schedule = scheduleService.getScheduleById(scheduleId);
        if (schedule == null) {
            System.out.println("场次不存在！");
            return;
        }

        System.out.print("请输入新的影片 ID（留空则不修改）：");
        String movieId = scanner.nextLine();
        if (!movieId.isEmpty()) {
            Movie movie = movieService.getMovieById(movieId);
            if (movie != null) {
                schedule.setMovie(movie);
            } else {
                System.out.println("影片不存在！");
                return;
            }
        }

        System.out.print("请输入新的放映厅 ID（留空则不修改）：");
        String hallId = scanner.nextLine();
        if (!hallId.isEmpty()) {
            CinemaHall hall = null;
            for (CinemaHall h : ((ScheduleServiceImpl) scheduleService).cinemaHalls) {
                if (h.getHallId().equals(hallId)) {
                    hall = h;
                    break;
                }
            }
            if (hall != null) {
                schedule.setCinemaHall(hall);
            } else {
                System.out.println("放映厅不存在！");
                return;
            }
        }

        System.out.print("请输入新的开始时间（格式：yyyy-MM-dd HH:mm:ss，留空则不修改）：");
        String startTimeStr = scanner.nextLine();
        if (!startTimeStr.isEmpty()) {
            Date startTime = DateUtil.parseDate(startTimeStr);
            schedule.setStartTime(startTime);
        }

        System.out.print("请输入新的票价（留空则不修改）：");
        String priceStr = scanner.nextLine();
        if (!priceStr.isEmpty()) {
            double price = Double.parseDouble(priceStr);
            schedule.setPrice(price);
        }

        boolean result = scheduleService.updateSchedule(schedule);
        if (result) {
            LogUtil.log("INFO", "修改场次成功，场次 ID：" + scheduleId, currentUser.getUsername());
            System.out.println("修改场次成功！");
        } else {
            System.out.println("修改场次失败！");
        }
    }

    private void deleteSchedule() {
        System.out.print("请输入要删除的场次 ID：");
        String scheduleId = scanner.nextLine();

        boolean result = scheduleService.deleteSchedule(scheduleId);
        if (result) {
            LogUtil.log("INFO", "删除场次成功，场次 ID：" + scheduleId, currentUser.getUsername());
            System.out.println("删除场次成功！");
        } else {
            System.out.println("删除场次失败！");
        }
    }

    private void listSchedules() {
        System.out.print("请输入日期（格式：yyyy-MM-dd，留空则显示所有场次）：");
        String dateStr = scanner.nextLine();
        Date date = null;
        if (!dateStr.isEmpty()) {
            date = DateUtil.parseDate(dateStr + " 00:00:00");
        }

        List<Schedule> schedules;
        if (date != null) {
            schedules = scheduleService.getSchedulesByDate(date);
        } else {
            schedules = scheduleService.getAllSchedules();
        }

        System.out.println("===== 场次列表 =====");
        System.out.println("场次 ID\t影片名称\t放映厅\t开始时间\t\t\t票价");
        for (Schedule schedule : schedules) {
            System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                    schedule.getCinemaHall().getHallName() + "\t" + DateUtil.formatDate(schedule.getStartTime()) + "\t" + schedule.getPrice());
        }
    }

    private void autoGenerateSchedule() {
        System.out.print("请输入开始日期（格式：yyyy-MM-dd）：");
        String startDateStr = scanner.nextLine();
        Date startDate = DateUtil.parseDate(startDateStr + " 00:00:00");

        System.out.print("请输入结束日期（格式：yyyy-MM-dd）：");
        String endDateStr = scanner.nextLine();
        Date endDate = DateUtil.parseDate(endDateStr + " 23:59:59");

        List<Movie> movies = movieService.getAllMovies();
        scheduleService.autoGenerateSchedule(movies, startDate, endDate);

        LogUtil.log("INFO", "自动排片成功，日期范围：" + startDateStr + " 至 " + endDateStr, currentUser.getUsername());
        System.out.println("自动排片成功！");
    }

    private void showSalesDataMenu() {
        while (true) {
            System.out.println("===== 销售数据查看 =====");
            System.out.println("1. 查看当日销售数据");
            System.out.println("2. 查看当周销售数据");
            System.out.println("3. 查看当月销售数据");
            System.out.println("4. 返回上一级");
            System.out.print("请选择操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    viewDailySalesData();
                    break;
                case "2":
                    viewWeeklySalesData();
                    break;
                case "3":
                    viewMonthlySalesData();
                    break;
                case "4":
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    private void viewDailySalesData() {
        System.out.print("请输入日期（格式：yyyy-MM-dd）：");
        String dateStr = scanner.nextLine();
        Date date = DateUtil.parseDate(dateStr + " 00:00:00");

        List<Schedule> schedules = scheduleService.getSchedulesByDate(date);
        double totalSales = 0.0;
        int totalTickets = 0;
        int totalRefunds = 0;
        double totalRefundAmount = 0.0;

        System.out.println("===== 当日销售数据 =====");
        System.out.println("场次 ID\t影片名称\t总票价\t退票数\t退票金额");
        for (Schedule schedule : schedules) {
            List<Ticket> tickets = ticketService.getTicketsByScheduleId(schedule.getScheduleId());
            int soldTickets = 0;
            int refundTickets = 0;
            double refundAmount = 0.0;
            for (Ticket ticket : tickets) {
                if (ticket.getStatus().equals("已售出")) {
                    soldTickets++;
                    totalTickets++;
                    totalSales += ticket.getPrice();
                } else if (ticket.getStatus().equals("已退票")) {
                    refundTickets++;
                    totalRefunds++;
                    refundAmount += ticket.getPrice();
                    totalRefundAmount += ticket.getPrice();
                }
            }
            System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                    soldTickets * schedule.getPrice() + "\t" + refundTickets + "\t" + refundAmount);
        }
        System.out.println("===== 总计 =====");
        System.out.println("总销售票数：" + totalTickets);
        System.out.println("总销售金额：" + totalSales);
        System.out.println("总退票数：" + totalRefunds);
        System.out.println("总退票金额：" + totalRefundAmount);
    }

    private void viewWeeklySalesData() {
        System.out.print("请输入开始日期（格式：yyyy-MM-dd）：");
        String startDateStr = scanner.nextLine();
        Date startDate = DateUtil.parseDate(startDateStr + " 00:00:00");

        System.out.print("请输入结束日期（格式：yyyy-MM-dd）：");
        String endDateStr = scanner.nextLine();
        Date endDate = DateUtil.parseDate(endDateStr + " 23:59:59");

        List<Schedule> schedules = scheduleService.getAllSchedules();
        double totalSales = 0.0;
        int totalTickets = 0;
        int totalRefunds = 0;
        double totalRefundAmount = 0.0;

        System.out.println("===== 当周销售数据 =====");
        System.out.println("场次 ID\t影片名称\t总票价\t退票数\t退票金额");
        for (Schedule schedule : schedules) {
            if (schedule.getStartTime().after(startDate) && schedule.getStartTime().before(endDate)) {
                List<Ticket> tickets = ticketService.getTicketsByScheduleId(schedule.getScheduleId());
                int soldTickets = 0;
                int refundTickets = 0;
                double refundAmount = 0.0;
                for (Ticket ticket : tickets) {
                    if (ticket.getStatus().equals("已售出")) {
                        soldTickets++;
                        totalTickets++;
                        totalSales += ticket.getPrice();
                    } else if (ticket.getStatus().equals("已退票")) {
                        refundTickets++;
                        totalRefunds++;
                        refundAmount += ticket.getPrice();
                        totalRefundAmount += ticket.getPrice();
                    }
                }
                System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                        soldTickets * schedule.getPrice() + "\t" + refundTickets + "\t" + refundAmount);
            }
        }
        System.out.println("===== 总计 =====");
        System.out.println("总销售票数：" + totalTickets);
        System.out.println("总销售金额：" + totalSales);
        System.out.println("总退票数：" + totalRefunds);
        System.out.println("总退票金额：" + totalRefundAmount);
    }

    private void viewMonthlySalesData() {
        System.out.print("请输入月份（格式：yyyy-MM）：");
        String monthStr = scanner.nextLine();
        String startDateStr = monthStr + "-01 00:00:00";
        String endDateStr = monthStr + "-31 23:59:59";
        Date startDate = DateUtil.parseDate(startDateStr);
        Date endDate = DateUtil.parseDate(endDateStr);

        List<Schedule> schedules = scheduleService.getAllSchedules();
        double totalSales = 0.0;
        int totalTickets = 0;
        int totalRefunds = 0;
        double totalRefundAmount = 0.0;

        System.out.println("===== 当月销售数据 =====");
        System.out.println("场次 ID\t影片名称\t总票价\t退票数\t退票金额");
        for (Schedule schedule : schedules) {
            if (schedule.getStartTime().after(startDate) && schedule.getStartTime().before(endDate)) {
                List<Ticket> tickets = ticketService.getTicketsByScheduleId(schedule.getScheduleId());
                int soldTickets = 0;
                int refundTickets = 0;
                double refundAmount = 0.0;
                for (Ticket ticket : tickets) {
                    if (ticket.getStatus().equals("已售出")) {
                        soldTickets++;
                        totalTickets++;
                        totalSales += ticket.getPrice();
                    } else if (ticket.getStatus().equals("已退票")) {
                        refundTickets++;
                        totalRefunds++;
                        refundAmount += ticket.getPrice();
                        totalRefundAmount += ticket.getPrice();
                    }
                }
                System.out.println(schedule.getScheduleId() + "\t" + schedule.getMovie().getName() + "\t" +
                        soldTickets * schedule.getPrice() + "\t" + refundTickets + "\t" + refundAmount);
            }
        }
        System.out.println("===== 总计 =====");
        System.out.println("总销售票数：" + totalTickets);
        System.out.println("总销售金额：" + totalSales);
        System.out.println("总退票数：" + totalRefunds);
        System.out.println("总退票金额：" + totalRefundAmount);
    }

    private void modifyPassword() {
        System.out.print("请输入旧密码：");
        String oldPassword = scanner.nextLine();
        System.out.print("请输入新密码：");
        String newPassword = scanner.nextLine();
        System.out.print("请再次输入新密码：");
        String confirmPassword = scanner.nextLine();

        if (!newPassword.equals(confirmPassword)) {
            System.out.println("两次输入的新密码不一致！");
            return;
        }

        if (userService.login(currentUser.getUsername(), oldPassword) != null) {
            boolean result = userService.resetPassword(currentUser.getUserId(), newPassword);
            if (result) {
                LogUtil.log("INFO", "修改密码成功，用户 ID：" + currentUser.getUserId(), currentUser.getUsername());
                System.out.println("修改密码成功！");
            } else {
                System.out.println("修改密码失败！");
            }
        } else {
            System.out.println("旧密码错误！");
        }
    }
}